package cn.shyouchi.wuguanjia.android.ui.train;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.Global;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.train.TrainApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.event.DataChangeEvent;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.GlideCircleTransform;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class TrainMasterActivity extends BaseActivity {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.tv_count_time)
    TextView mTvCountTime;
    @BindView(R.id.img_master_header)
    ImageView mImgMasterHeader;
    @BindView(R.id.tv_master_name)
    TextView mTvMasterName;
    @BindView(R.id.tv_master_age)
    TextView mTvMasterAge;
    @BindView(R.id.tv_master_height)
    TextView mTvMasterHeight;
    @BindView(R.id.tv_master_work)
    TextView mTvMasterWork;
    @BindView(R.id.tv_master_worktime)
    TextView mTvMasterWorktime;
    @BindView(R.id.tv_master_chepai)
    TextView mTvMasterChepai;
    @BindView(R.id.tv_master_phone)
    TextView mTvMasterPhone;
    @BindView(R.id.tv_matser_other)
    TextView mTvMatserOther;
    @BindView(R.id.tv_prio)
    TextView mTvPrio;
    @BindView(R.id.tv_next)
    TextView mTvNext;

    TrainApi mTrainApi;

    boolean canLoad = true;

    int curPage = 0;
    int maxPage;

    MasterEntity mMasterEntity;


    @Override
    public int initContentView() {
        return R.layout.activity_train_master;
    }

    @Override
    public void initInjector() {
        mTrainApi = new TrainApi();
        curPage = getIntent().getIntExtra("curPage", 1);
        maxPage = getIntent().getIntExtra("maxPage", 1);
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        mTopBar.setTitle(getTitle().toString());
        setSupportActionBar(mTopBar.getToolbar());
        fetchMasterData(curPage);
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @OnClick({R.id.tv_prio, R.id.tv_next})
    public void onClick(View view) {
        if (canLoad) {
            switch (view.getId()) {
                case R.id.tv_prio:
                    if (curPage - 1 > 0) {
                        curPage--;
                        fetchMasterData(curPage);
                    } else {
                        ToastUtil.showToast("没有了");
                    }
                    break;
                case R.id.tv_next:
                    if (curPage + 1 <= maxPage) {
                        curPage++;
                        fetchMasterData(curPage);
                    } else {
                        ToastUtil.showToast("没有了");
                    }
                    break;
            }
        } else {
            ToastUtil.showToast(mTvCountTime.getText() + "后才能加载");
        }
    }


    private void fetchMasterData(int page) {


        mTrainApi.getMasterData(page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<BaseRequestResult<MasterEntity>>(mContext) {
                    @Override
                    public void onNext(BaseRequestResult<MasterEntity> listBaseRequestResult) {
                        fillData(listBaseRequestResult.getResultMessage());
                    }
                });
    }


    private void fillData(MasterEntity entity) {
        mMasterEntity = entity;
        mTvMasterAge.setText(entity.getAge() + "岁");
        mTvMasterHeight.setText(String.valueOf(entity.getHeight()));
        mTvMasterWork.setText(entity.getJob());
        mTvMasterWorktime.setText(entity.getWorkinghours());
        mTvMasterChepai.setText(entity.getNumberplates());
        mTvMasterPhone.setText(entity.getPhone());
        mTvMatserOther.setText(entity.getRemarks());
        mTvMasterName.setText(String.format("%s/%s", entity.getName(), entity.getSex() == 1 ? "男" : "女"));
        loadHead(Global.BASE_URL + entity.getImages(), mImgMasterHeader);

        if (!entity.isWhether()) {
            EventBus.getDefault().post(new DataChangeEvent());
            startCount();
        }

    }


    private Observable<Integer> countdown(int time) {
        if (time < 0) time = 0;
        final int countTime = time;
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<Long, Integer>() {
                    @Override
                    public Integer call(Long increaseTime) {
                        return countTime - increaseTime.intValue();
                    }
                })
                .take(countTime + 1);
    }


    private void startCount() {
        countdown(30)
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        canLoad = false;
                        mTvCountTime.setVisibility(View.VISIBLE);
                    }
                })
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {
                        canLoad = true;
                        mTvCountTime.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Integer integer) {
                        mTvCountTime.setText(integer + "s");
                    }
                });
    }


    private void loadHead(String path, ImageView imageView) {
        Glide.with(mContext)
                .load(path)
                .transform(new GlideCircleTransform(mContext))
                .into(imageView);
    }

}
